package com.etop.controller;

import com.etop.beans.Activity;
import com.etop.beans.Borrow;
import com.etop.beans.ProFile;
import com.etop.beans.Pro_schedule;
import com.etop.beans.Project;
import com.etop.beans.Registration;
import com.etop.beans.User;
import com.etop.dto.UserGoodsDTO;
import com.etop.service.UserService;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

@Controller
@SessionAttributes({"loginUser","users"})               // 把用户对象保存在session中，名字为"loginUser"
public class UserController {

    @Resource(name = "userService")           // 注入userService对象，new userService()在applicationContext.xml中配置
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户权限不足便转向index.jsp
     *
     * @param model
     * @return
     */
    @RequestMapping(value = {"/index"}, method = RequestMethod.GET)
    public String index(Model model) {
        return "index";
    }

    /**
     * 登陆功能的后台验证
     */
    @RequestMapping(value = {"/login"}, method = RequestMethod.POST)     // post可以隐藏url上的参数
    public String login(String stuNum, String password, Model model) {
        User user = new User(stuNum, password);
        user = userService.loginValidate(user);
        if (user == null) {
            model.addAttribute("result", "error");
            return "index";
        } else if (user.getIsAdmin() == 0) {                   // 普通用户的角色
            model.addAttribute("loginUser", user);
            boolean isRegistered = userService.registerValidate(user);
            if (isRegistered) {
                model.addAttribute("isRegistered", isRegistered);
            }
            return "user/login";
            //return "redirect:/logined";
        } else {                                               // 管理员的角色
            List<User> users = userService.listOfAllUsers();
            model.addAttribute("users", users);
            model.addAttribute("loginUser", user);
            return "admin/login";
        }
    }

    @RequestMapping(value = {"/registry"}, method = RequestMethod.GET)
    public String registry(Model model) {
        User user = (User) model.asMap().get("loginUser");
        userService.addRegister(user);
        boolean isRegistered = true;
        model.addAttribute("isRegistered", isRegistered);
        return "user/login";
    }

    /**
     * 退出登陆
     */
    @RequestMapping(value = {"/loginout"}, method = RequestMethod.GET)
    public String loginout(Model model, HttpSession session) {
        model.asMap().remove("loginUser");
        session.invalidate();
        return "index";
    }

    @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
    public String toLogin(Model model) {
        User user = (User) model.asMap().get("loginUser");
        if (user.getIsAdmin() == 0) {                   // 普通用户的角色
            return "user/login";
        } else {                                               // 管理员的角色
            return "admin/login";
        }
    }

    /**
     * 跳转到物品中心
     *
     * @param search 要查找的物品
     * @param model
     * @return
     */
    @RequestMapping(value = {"/GoodsCenter"}, method = RequestMethod.GET)
    public String chackGoods(String search, Model model) {
        if (null == search) {
            search = "";
        }
        List<UserGoodsDTO> listUserGoodsDTO = userService.listUserGoodsDTO(search);
        model.addAttribute("listUserGoodsDTO", listUserGoodsDTO);
        return "user/GoodsCenter";
    }

    /**
     * 借物品
     *
     * @param returnDay 预计还书的日期
     * @param gid 借书的id
     * @param session 用于获取借书的用户
     * @return
     */
    @RequestMapping(value = {"/borrow"}, method = RequestMethod.POST)
    public String borrow(String returnDay, int gid, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        Date returnDate = null;
        try {
            returnDate = DateFormat.getDateInstance().parse(returnDay);
        } catch (ParseException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
        Borrow borrow = new Borrow(new Date(), returnDate, user, null);
        if (userService.addBorrow(borrow, gid)) {
            return "redirect:/GoodsCenter";
        } else {
            System.out.println("ERROR");
            return "user/login";
        }
    }

    /**
     * 处理归还物品
     *
     * @param bid 借物品的id
     * @return
     */
    @RequestMapping(value = {"/returnGoods"}, method = RequestMethod.POST)
    public String returnGoods(int bid) {
        System.out.println(bid);
        userService.updateBorrow(bid);
        return "redirect:/borrowInformation";
    }

    /**
     * 跳转去上传界面
     *
     * @param m 用于向界面中传送项目的信息
     * @return
     */
    @RequestMapping(value = {"/upload"}, method = RequestMethod.GET)
    public String fileUpload(Model m) {
        List<Project> projectList = userService.listProject();
        m.addAttribute("projectList", projectList);
        return "user/upload";
    }

    /**
     * 处理上传
     *
     * @param proID 添加文件的项目的id
     * @param multipartFile 里面包含要上传的文件
     * @param request
     * @return
     */
    @RequestMapping(value = {"/upload"}, method = RequestMethod.POST)
    public String fileUpload(int proID, MultipartFile multipartFile, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("loginUser");
        userService.addProFile(proID, multipartFile, request.getContextPath(), user.getUserName());
        return "redirect:/fileUpload";
    }

    /**
     * 跳转到查看文件的页面
     *
     * @param proName 文件所在的项目名（可不要）
     * @param m
     * @return
     */
    @RequestMapping(value = {"/chackFile"}, method = RequestMethod.GET)
    public String chackFile(String proName, Model m) {
        if (proName == null) {
            proName = "";
        }
        List<ProFile> proFileList = userService.listProFile(proName);
        m.addAttribute("proFileList", proFileList);
        return "user/chackFile";
    }

    /**
     * 处理下载
     *
     * @param proFileId 下载文件的id
     * @param response 获取输出流
     */
    @RequestMapping(value = {"/downLoadFile"}, method = RequestMethod.GET)
    public void downLoadFile1(int proFileId, HttpServletResponse response) {
        userService.downLoadFile(proFileId, response);
        //return "redirect:/chackFile";
    }

    /**
     * 活动详情的后台操作
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = {"/project-introduction"}, method = RequestMethod.GET)
    public String project_introduction(int id, Model model) {
        Activity oneAct = userService.oneActivity(id);
        List<String> listMember = userService.listMembersOfAct(oneAct);
        model.addAttribute("oneAct", oneAct);
        model.addAttribute("actMembers", listMember);
        return "user/project-introduction";
    }

    /**
     * 活动列表的后台操作
     *
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = {"/project-register"}, method = RequestMethod.GET)
    public String project_register(Model model, HttpSession session) {
        List<Activity> list = userService.listOfActivity((User) session.getAttribute("loginUser"));
        model.addAttribute("activity", list);
        return "user/project-register";
    }

    /**
     * 活动报名成功的后台操作
     *
     * @param acti_id
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = {"/project-register"}, method = RequestMethod.POST)
    public String project_register(int acti_id, Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        List<Activity> list = userService.listOfActivity(user);
        model.addAttribute("activity", list);
        if (userService.addMemberInActivity(user, acti_id) == true) {
            for (Activity list1 : list) {
                if (list1.getId() == acti_id) {
                    list1.setIsAdded(1);
                    break;
                }
            }
        } else {
            model.addAttribute("addResult", "error");
        }
        return "user/project-register";
    }

    /**
     * 所有项目的查看
     *
     * @param model
     * @return
     */
    @RequestMapping(value = {"/projectManagement"}, method = RequestMethod.GET)
    public String projectManagement(Model model) {
        List<Project> pros = userService.listOfProject();
        List<Pro_schedule> sches = userService.listOfProSchedule();

        model.addAttribute("pros", pros);
        for (Project pros1 : pros) {
            pros1.setListOfLeaders(userService.listLeadersOfOneProject(pros1));
            pros1.setListOfMembers(userService.listMembersOfOneProject(pros1));
            pros1.setListOfSchedules(userService.listSchedulesOfOneProject(sches, pros1));
        }
        return "user/projectManagement";
    }

    /**
     * 个人项目的查看
     *
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = {"/myProject"}, method = RequestMethod.GET)
    public String myProject(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        List<Project> pros = userService.listProjectsOfUser(user);
        List<Pro_schedule> sches = userService.listOfProSchedule();
        List<User> listUsers = userService.listOfAllUsers();

        model.addAttribute("listUsers", listUsers);
        model.addAttribute("userPros", pros);
        for (Project pros1 : pros) {
            pros1.setListOfLeaders(userService.listLeadersOfOneProject(pros1));
            pros1.setListOfMembers(userService.listMembersOfOneProject(pros1));
            pros1.setListOfSchedules(userService.listSchedulesOfOneProject(sches, pros1));
        }
        return "user/myProject";
    }

    /**
     * 对提交的进度描述进行保存
     *
     * @param sche_desc
     * @param p_id
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = {"/myProject"}, method = RequestMethod.POST)
    public String myProject(String sche_desc, int p_id, Model model, HttpSession session) {
        Pro_schedule pro_sche = new Pro_schedule(new Date(), sche_desc, p_id);
        userService.addPro_schedule(pro_sche);
        User user = (User) session.getAttribute("loginUser");
        List<Project> pros = userService.listProjectsOfUser(user);
        List<Pro_schedule> sches = userService.listOfProSchedule();
        List<User> listUsers = userService.listOfAllUsers();

        model.addAttribute("listUsers", listUsers);
        model.addAttribute("userPros", pros);
        for (Project pros1 : pros) {
            pros1.setListOfLeaders(userService.listLeadersOfOneProject(pros1));
            pros1.setListOfMembers(userService.listMembersOfOneProject(pros1));
            pros1.setListOfSchedules(userService.listSchedulesOfOneProject(sches, pros1));
        }
        return "user/myProject";
    }

    /**
     * 添加项目
     *
     * @param projectName 项目名字
     * @param projectPersonInCharge 项目负责人
     * @param addProjectMember 项目成员
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = {"/addMyProject"}, method = RequestMethod.POST)
    public String addMyProject(String projectName, String projectPersonInCharge, String addProjectMember, Model model, HttpSession session) {
        Project project = new Project(projectName, 0, "暂无描述", new Date());
        userService.addProject(project);
        userService.addListOfUser_Project(addProjectMember, projectName, 0);
        userService.addListOfUser_Project(projectPersonInCharge, projectName, 1);

        User user = (User) session.getAttribute("loginUser");
        List<Project> pros = userService.listProjectsOfUser(user);
        List<Pro_schedule> sches = userService.listOfProSchedule();
        List<User> listUsers = userService.listOfAllUsers();

        model.addAttribute("listUsers", listUsers);
        model.addAttribute("userPros", pros);
        for (Project pros1 : pros) {
            pros1.setListOfLeaders(userService.listLeadersOfOneProject(pros1));
            pros1.setListOfMembers(userService.listMembersOfOneProject(pros1));
            pros1.setListOfSchedules(userService.listSchedulesOfOneProject(sches, pros1));
        }
        return "user/myProject";

    }

    @RequestMapping(value = {"/attendanceHistory"}, method = RequestMethod.GET)
    public String showAttendanceHistory(Model model) {
        User user = (User) model.asMap().get("loginUser");
        List<Registration> registrations = userService.showRegistrations(user);
        model.addAttribute("registrations", registrations);
        return "user/attendanceHistory";
    }

    @RequestMapping(value = {"/borrowInformation"}, method = RequestMethod.GET)
    public String showBorrowInfo(Model model) {
        User user = (User) model.asMap().get("loginUser");
        List<Borrow> borrowInfos = userService.showBorrowInfo(user);
        model.addAttribute("borrowInfos", borrowInfos);
        return "user/borrowInformation";
    }

    @RequestMapping(value = {"/modify"}, method = RequestMethod.GET)
    public String updateInfo(Model model) {
        return "user/modify";
    }

    @RequestMapping(value = {"/modify.do"}, method = RequestMethod.POST)
    public String updateConfirmInfo(@Validated User loginUser, BindingResult rb, Model model) {
        model.addAttribute("loginUser", loginUser);
        userService.updateInfo(loginUser);
        return "user/login";
    }

    @RequestMapping(value = {"/modifyPassword"}, method = RequestMethod.GET)
    public String updatePassword(Model model) {
        return "user/modifyPassword";
    }

    @RequestMapping(value = {"/modifyPassword"}, method = RequestMethod.POST)
    public String updateConfirmPassword(String original, String originalInput, String modify, Model model) {
        Boolean isErrored = userService.passwordValidate(original, originalInput);
        if (!isErrored) {
            model.addAttribute("error", "原密码不正确");
            return "user/modifyPassword";
        } else {
            User loginUser = (User) model.asMap().get("loginUser");
            userService.updatePassword(loginUser, modify);
            model.asMap().remove("loginUser");
            return "redirect:/index";
        }
    }
}
